import os
import random
import string

import dashscope
import requests
from PIL import Image
from flask import jsonify, request, send_from_directory, Blueprint

from ai_layer.chat.qwen import answer
from app.image_identify import generate_chemical_formula_image, text_identify, formula_to_smiles
from ai_layer.abstrations.ai_service import AIGenerator
from ai_layer.moderation.ai_security import AISecurity
from utils.paint import drawImg

dashscope.api_key = 'example_api_key'

ai_api = Blueprint('ai_api', __name__)

# 从配置中读取当前模型和 API 密钥（示例）
CURRENT_PROVIDER = "qwen"
API_KEY = "example_api_key"

# 初始化生成器和安全审查
ai_generator = AIGenerator(CURRENT_PROVIDER, API_KEY)
security_checker = AISecurity()


@ai_api.route('/ping', methods=['GET'])
def ping():
    return jsonify({'message': 'pong!'})


@ai_api.route('/image/<path:filename>')
def custom_static(filename):
    return send_from_directory('../static', filename)


@ai_api.route('/v1/draw', methods=['POST'])
def draw():
    idx = request.json.get('id')
    data = request.json.get('data')
    style = request.json.get('style')
    uid = request.json.get('uid')  # 获取用户唯一标识符
    if idx is None or uid is None:
        return jsonify({
            'code': 500,
            'message': "参数错误",
            'data': ''
        })
    if style is None:
        style = '二次元'

    # 简笔画图片路径
    file_path = os.path.join("static", "files", "line_drawing.png")

    drawImg(data, file_path)

    print('分类id：', idx)
    category_str = get_category(idx)
    style_str = get_style(style)
    prompt = f"这是一个或多个{category_str}，生成的图片要求符合原画，内容简单，线条感分明，色彩简单，较差的画画水平"
    print(prompt)
    sketch_image_url = file_path

    # 化学精灵部分
    if category_str == '化学分子式':
        text = text_identify(file_path)
        print("识别化图片文字：", text)
        if text != '':
            chemical_formula = answer(text)
            print("识别化学式为：", chemical_formula)
            smiles = formula_to_smiles(chemical_formula)
            print("转化的smiles：", smiles)
            if smiles is not None:
                filename = generate_chemical_formula_image(smiles)
                return jsonify({"code": 200, "data": {"results": filename}})

    #  输入安全审查
    safe_input = security_checker.check_input({
        "prompt": prompt,
        "style": style,
        "sketch_path": sketch_image_url
    })

    # 调用AI生成
    result = ai_generator.generate_image(**safe_input)

    # 输出安全审查
    safe_output = security_checker.check_output(result)
    print(safe_output)
    if safe_output["success"]:
        filename = download_image(safe_output["url"])
        print(filename)

        # 保存图片信息到数据库
        # save_image_info_to_db(uid, filename)

        return jsonify({"code": 200, "data": {"results": filename}})
    else:
        return jsonify({"code": 500, "message": result["error"]})


def get_category(value):
    if value == '1':
        return "水果"
    elif value == '2':
        return "花草"
    elif value == '3':
        "动物"
    else:
        return "化学分子式"


def get_style(value):
    if value == '3D卡通':
        return '<3d cartoon>'
    elif value == '二次元':
        return '<anime>'
    elif value == '油画':
        return '<oil painting>'
    elif value == '水彩':
        return '<watercolor>'
    elif value == '素描':
        return '<sketch>'
    elif value == '中国画':
        return '<chinese painting>'
    else:
        return '<auto>'


def download_image(image_url):
    try:
        response = requests.get(image_url, stream=True)
        response.raise_for_status()
        tmp_path = os.path.join('static', get_filename('ai-'))
        with open(tmp_path, 'wb') as file:
            for chunk in response.iter_content(1024):
                file.write(chunk)

        print(f"图片已保存到: {tmp_path}")
        filename = get_filename()
        save_path = os.path.join('static', filename)
        # 压缩图片
        handle_image(tmp_path, save_path)
        return filename
    except requests.exceptions.RequestException as e:
        print(f"下载图片时出错: {e}")
        return ''


def handle_image(input_path, output_path, max_size_kb=15, resize_factor=0.3, quality=85):
    with Image.open(input_path) as img:
        if img.mode in ("RGBA", "P"):
            img = img.convert("RGB")
        while True:
            img.save(output_path, format="JPEG", quality=quality)
            size_kb = os.path.getsize(output_path) / 1024
            if size_kb <= max_size_kb or quality <= 10:
                print(f"压缩完成，文件大小：{size_kb:.2f} KB，最终质量：{quality}")
                break
            width, height = img.size
            img = img.resize(
                (int(width * resize_factor), int(height * resize_factor)),
                Image.Resampling.LANCZOS
            )
            quality -= 5


def generate_random_string(length=15):
    letters = string.ascii_letters
    return ''.join(random.choice(letters) for _ in range(length))


def get_filename(prefix=''):
    return prefix + generate_random_string() + '.png'


def directory_exists(directory_path):
    # 判断目录是否存在
    if not os.path.exists(directory_path):
        # 如果不存在，则创建目录
        os.makedirs(directory_path)
        print(f"目录 {directory_path} 已创建。")
    else:
        print(f"目录 {directory_path} 已存在。")
